package com.tanhua.admin.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tanhua.admin.service.LogService;
import com.tanhua.model.db.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class LogListener {

    @Autowired
    private LogService logService;

    /**
     * durable 持久化
     * bindings: 绑定. 交换机与队列,通过什么 key (routingKey)
     * @Queue: 声明队列, 不存在则创建 value|name 队列名
     * @Exchange: 声明交换机,不存在则创建, value交换机名称, type=交换机模型: TOPIC主题模式
     * key: routingKey *：1个单词，#:0或多个单词
     * @param message
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "tanhua.log.queue", durable = "true"),
            exchange = @Exchange(value = "tanhua.log.exchange", type = ExchangeTypes.TOPIC),
            key = {"log.*"}
    ))
    public void addLog(String message){
        log.info("记录log日志: {}", message);
        //1. 解析消息内容
        JSONObject jsonObject = JSON.parseObject(message);
        //2. 构建pojo
        Log pojo = new Log();
        pojo.setUserId(jsonObject.getLong("userId"));
        pojo.setEquipment("iphone13max");
        pojo.setPlace("深圳黑马");
        pojo.setLogTime(jsonObject.getString("logTime"));
        pojo.setType(jsonObject.getString("type"));
        //3. 添加log记录
        logService.add(pojo);
    }
}